package com.hgy.carsb.service;

import com.hgy.carsb.dao.DataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;

@Service
public class InfoService {
    @Autowired
    private DataMapper dataMapper;

    public String getRatio(int year, int month, String code1, String code2, String prefix){
        String num1 = getThisMonth(year, month, code1, prefix);
        String num2 = getThisMonth(year, month, code2, prefix);
        BigDecimal n1 = new BigDecimal(num1);
        BigDecimal n2 = new BigDecimal(num2);
        if (n2.toString().equals("0")){
            return "0";
        }else {
            n1 = n1.multiply(new BigDecimal(100)).divide(n2, 2, BigDecimal.ROUND_HALF_UP);
        }
        return n1.toString();
    }

    public String getThisMonth(int year, int month, String zbCode, String prefix){
        String pre = "INTF_DATA_";
        String num = "0";
        String tableName = "";
        if (month<=9){
            tableName = pre+year+"Y000"+month;
        }else {
            tableName = pre+year+"Y00"+month;
        }
        if (!isExist(tableName)){
            return num;
        }
        num = dataMapper.getValueByCode(tableName, zbCode, prefix);
        return num;
    }
    public boolean isExist(String tableName){
        return dataMapper.isExist(tableName) != null;
    }

    public String getYearSum(int year, int month, String zbCode, String prefix){
        String num = "0";
        BigInteger sum = new BigInteger(num);
        for (int i=1; i<=month; i++){
            num = getThisMonth(year, i, zbCode, prefix);
            sum = sum.add(new BigInteger(num));
        }
        return sum.toString();
    }
}
